//index.js
//获取应用实例
const app = getApp()
const moment = require('../../utils/moment.js');
Page({
  data: {
    date: null,
    dateImg: "../../images/sign-date.png",
    listCustom: [],
    addCustom: {
      url: '../add_custom/add_custom',
      add_pic: '../../images/add.png'
    },
    customList: [],
    customLogs: []
  },
  //获取选定的时间
  bindDateChange: function (e) {
    console.log(e.detail.value)
    this.setData({
      date: e.detail.value
    })
    // 刷新列表显示
    this.makeList()
  },
  deleteCustom: function (event) {
    console.log('delete')
    let page = this
    let custom = event.currentTarget.dataset.custom
    wx.showModal({
      title: '删除习惯【' + custom + '】？',
      content: '数据将不可恢复！',
      showCancel: true,
      confirmText: '确定删除',
      success: function (res) {
        console.log(res)
        if (res.confirm) {
          page.deleteCustomData(custom).then(res => {
            // 刷新列表显示
            page.makeList()
          })
        }
      }
    })
  },
  clickCustom: function (event) {
    let page = this
    let custom = event.currentTarget.dataset.custom

    let today = moment().format('YYYY-MM-DD')
    if (page.data.date === today) {
      wx.showModal({
        title: '提示',
        content: '你今天已经完成了【' + custom + '】吗？',
        showCancel: true,
        confirmText: '确定',
        success: function (res) {
          console.log(res)
          if (res.confirm) {
            page.saveCustomLog(custom).then(data => {
              console.log(data)
              page.makeList()
            })
          }
        }
      })
    } else {
      if (page.data.date > today) {
        wx.showModal({
          title: '不能提前打卡喔',
          content: page.data.date + '还没到呢~不能提前打卡喔~',
          confirmText: '知道啦',
          showCancel: false
        })
      } else {
        wx.showModal({
          title: '不能补打喔',
          content: page.data.date + '已经是过去式啦~不能补打喔~',
          confirmText: '知道啦',
          showCancel: false
        })
      }
    }
  },
  // 保存此习惯的打卡数据
  saveCustomLog (custom) {
    // 查找数据对象
    let customLog = null
    this.data.customLogs.forEach(item => {
      if (item.custom === custom) {
        customLog = item
      }
    })

    if (customLog) {
      customLog.value = true
      return app.apis().updateCustomLog(customLog.id, customLog)
    }
  },
  deleteCustomData(customName) {
    // 查找数据对象
    let custom = null
    let customLog = null
    this.data.customList.forEach(item => {
      if (item.name === customName) {
        custom = item
      }
    })
    this.data.customLogs.forEach(item => {
      if (item.custom === customName) {
        customLog = item
      }
    })

    let promises = []
    if (custom) {
      promises.push(app.apis().deleteCustom(custom.id))
    }
    if (customLog) {
      promises.push(app.apis().deleteCustomLog(customLog.id))
    }
    return Promise.all(promises)
  },
  initTodayCustomLogs: function() {
    return new Promise((resolve, reject) => {
      let today = moment().format('YYYY-MM-DD')
      Promise.all([
        app.apis().getCustoms(app.globalData.userObject.id),
        app.apis().getCustomLogs(app.globalData.userObject.id, today)
      ]).then(function (data) {
        let customList = data[0]._embedded.custom
        let customLogs = data[1]._embedded.custom_logs
        console.log(customList, customLogs)
        let promises = []
        customList.forEach(custom => {
          let needAdd = true
          customLogs.forEach(customLog => {
            if (custom.name === customLog.custom) needAdd = false
          })

          if (needAdd) {
            promises.push(app.apis().addCustomLog(app.globalData.userObject.id, today, custom.name))
          }
        })

        Promise.all(promises).then(function () {
          resolve()
        })
      })
    })
  },
  makeList () {
    let that = this
    let date = this.data.date
    let today = moment().format('YYYY-MM-DD')

    let customList = [];
    let customLogs = [];
    let list_data = [];

    this.initTodayCustomLogs().then(() => {
      return Promise.all([
        app.apis().getCustoms(app.globalData.userObject.id),
        app.apis().getCustomLogs(app.globalData.userObject.id, date)
      ])
    }).then(function (data) {
      customList = data[0]._embedded.custom
      customLogs = data[1]._embedded.custom_logs

      if (date < today) {
        // 正在显示以往的打卡列表
        customLogs.forEach(customLog => {
          list_data.push({
            custom_name: customLog.custom,
            custom_pic: customLog.value ? '../../images/smile_face.png' : '../../images/cry_face.png',
            show_delete: false
          })
        })
      } else if (date > today) {
        // 正在显示未来的打卡列表
        customList.forEach(item => {
          list_data.push({
            custom_name: item.name,
            custom_pic: '../../images/cry_face.png',
            show_delete: false
          })
        })
      } else if (date === today) {
        // 正在显示当天的打卡列表
        customLogs.forEach(customLog => {
          list_data.push({
            custom_name: customLog.custom,
            custom_pic: customLog.value ? '../../images/smile_face.png' : '../../images/cry_face.png',
            show_delete: true
          })
        })
      }
      that.setData({
        customList,
        customLogs,
        listCustom: list_data
      })
    })
  },
  onShow () {
    this.makeList()
  },
  onLoad (query) {
    // 把日期选择器的时间设置为当天
    this.setData({
      date: moment().format('YYYY-MM-DD')
    })
  }
})
